import React, { useState, useRef, useEffect } from 'react';
import { ProCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Space, Table, Tag, Modal } from 'antd';
import type { Key } from 'antd/lib/table/interface';
import DetialList from '../detialList';
import NewMessage from '../newMessage';
import RegisterandPayDetail from '../registerandPayDetail';
import { PageContainer } from '@ant-design/pro-layout'
import { connect } from 'umi';
import { Upload, message } from 'antd';
import { values } from 'lodash';
const notifications = [
    '学习计划会议将于明天召开，请准时参加。',
    '本周体育活动推迟至下周，请做好准备。',
    '学校开展环境保护志愿者招募，请有兴趣的同学报名。',
    '各班班长请于本周五参加班长会议。',
    '团委组织乡村义务劳动活动，报名截止本周五。',
    '辅导员将于明天下午在办公室接待同学。',
];
const statusMap = [
    {
        color: 'green',
        text: '已读',
    },
    {
        color: 'red',
        text: '未读',
    },
];
export type Status = {
    color: string;
    text: string;
};
export type TableListItem = {
    id: number;
    key: number;
    receiverCount: number;
    readCount: number;
    title: string;
    createTime: number;
};
export type DetialTableListItem = {
    key: number;
    stuName: string;
    callNumber: string;
    status: Status;
    isRead: string;
    stuCode: string;
    phoneNumber: string;
    majorLabel: string;
    classLabel: string;
    recipt: string;
    isFile: number;
    isForm: number;
    isUpLoad: string;
    isFormFilled: string;
};
//制造假数据
const tableListDataSource: TableListItem[] = [];
for (let i = 0; i < 50; i += 1) {
    tableListDataSource.push({
        id: i,
        key: i,
        receiverCount: Math.floor(Math.random() * 1000),
        readCount: Math.floor(Math.random() * 1000),
        title: notifications[Math.floor(Math.random() * notifications.length)],
        createTime: Date.now() - Math.floor(Math.random() * 100000),
    });
}


const MessageList: React.FC = (props: any) => {
    // 使用useState钩子创建表格数据源的状态变量tableListData
    const [tableListData, setTableListData] = useState<TableListItem[]>();
    const [detialTableListData, setDetialTableListData] = useState<DetialTableListItem[]>();
    const [notificationId, setNotificationId] = useState("");
    // 使用useState钩子创建状态变量，用于存储用户选择的行的keys
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
    const columns: ProColumns<TableListItem>[] = [
        {
            title: '序号',
            align: 'center',
            width: 120,
            dataIndex: 'key',
        },
        {
            title: '通知主题',
            width: 600,
            align: 'left',
            dataIndex: 'title',
        },
        {
            title: '通知人数',
            width: 120,
            align: 'center',
            dataIndex: 'receiverCount',
        },
        {
            title: '已读人数',
            width: 120,
            align: 'center',
            dataIndex: 'readCount',
        },
        {
            title: '创建时间',
            width: 140,
            key: 'since',
            dataIndex: 'createTime',
            valueType: 'date',
            sorter: (a, b) => a.createTime - b.createTime,
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (_, record) => (
                <Space size="middle">
                    <Button type="primary" onClick={() => { showSelect(record.id) }}>
                        查看详情
                    </Button>
                    <Button danger type="primary" onClick={() => { showdelete(record.id) }} >
                        删除通知
                    </Button>
                </Space>
            ),
        },
    ];
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isMessageOpen, setIsMessageOpen] = useState(false);
    const [isPayOpen, setIsPayOpen] = useState(false);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);
    const [deleteId, setDeleteID] = useState("")
    const showSelect = (value: any) => {
        if (value == '1688102157292683266') {
            showPay()
        }
        else { showModal(), getDetialList(value) }
    }
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const showMessage = () => {
        setIsMessageOpen(true);
    };
    const MessageOk = () => {
        setIsMessageOpen(false);
    };
    const MessageCancel = () => {
        setIsMessageOpen(false);
    };
    const showPay = () => {
        setIsPayOpen(true);
    };
    const PayOk = () => {
        setIsPayOpen(false);
    };
    const PayCancel = () => {
        setIsPayOpen(false);
    };
    const showdelete = (value: any) => {
        setDeleteID(value)
        setIsDeleteOpen(true);
    };
    const DeleteOk = () => {
        deleteList(deleteId)
        setIsDeleteOpen(false);
    };
    const deleteMessageCancel = () => {
        setIsDeleteOpen(false);
    };

    const getDetialList = (value: any) => {
        setNotificationId(value)
        if (props.dispatch) {
            console.log("获取详情列表")
            props.dispatch({
                //路径：model的namespace+effects函数名
                type: 'Model_Counsellor/getDetialListEffects',
                payload: {
                    value: value,
                    callback: (value: any) => {
                        console.log(value)
                        value?.forEach(item => {
                            if (item.isRead == 1 || item.isRead == "1") {
                                item.status = statusMap[0]
                            }
                            else { item.status = statusMap[1] }
                            if (item.isForm == 1 && item.formContent) {
                                item.receipt = JSON.parse(item.formContent).value
                                console.log(item.receipt)
                            } else item.receipt = ""
                            console.log(item.isFormFilled)
                            if (item.isFormFilled == "1") item.isUpLoad = "是"
                            else item.isUpLoad = "否"
                        })
                        setDetialTableListData(value)
                    },
                },
            });
        }
    };
    const deleteList = (value: any) => {
        if (props.dispatch) {
            console.log("删除通知")
            props.dispatch({
                //路径：model的namespace+effects函数名
                type: 'Model_Counsellor/deleteListEffects',
                payload: {
                    id: value,
                    callback: (value: any) => {
                        if (value) {
                            message.success("删除成功")
                            window.location.reload()
                        }
                    }
                },
            });
        }
    }
    const getAllList = () => {
        if (props.dispatch) {
            props.dispatch({
                //路径：model的namespace+effects函数名
                type: 'Model_Counsellor/getMessageListEffects',
                payload: {
                    value: localStorage.getItem('userAccount'),
                    callback: (value: any) => {
                        setTableListData(value)

                    },
                },
            });
        }
    };
    useEffect(() => {
        getAllList();
    }, [props]);
    return (
        <PageContainer>
            <div>
                <ProCard title="通知列表">
                    <Button onClick={showMessage}>新建通知</Button>
                    <Modal open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={1000}>
                        <DetialList
                            getDetialTableListData={detialTableListData}
                            notificationId={notificationId}
                        ></DetialList>
                    </Modal>
                    <Modal open={isPayOpen} onOk={PayOk} onCancel={PayCancel} width={2000}>
                        <RegisterandPayDetail></RegisterandPayDetail>
                    </Modal>
                    <Modal title="删除此通知吗？" open={isDeleteOpen} onOk={() => { DeleteOk() }} onCancel={deleteMessageCancel}>
                    </Modal>
                    <Modal open={isMessageOpen} onOk={MessageOk} footer={null} onCancel={MessageCancel} width={1000}>
                        <NewMessage
                            notificationId={notificationId}
                        ></NewMessage>
                    </Modal>
                    <ProTable<TableListItem>
                        columns={columns}
                        //配置表格的行选择功能。
                        rowSelection={{
                            selectedRowKeys, // 设置用户选择的行
                            onChange: (keys) => setSelectedRowKeys(keys), // 更新用户选择的行
                            selections: [
                                Table.SELECTION_ALL, //全选
                                Table.SELECTION_INVERT, //反选
                                Table.SELECTION_NONE, //全不选
                            ],
                        }}
                        //自定义表格顶部的操作选项，通常用于添加自定义操作按钮。
                        tableAlertOptionRender={() => {
                            return (
                                <Space size={16}>
                                    <a>导出数据</a>
                                </Space>
                            );
                        }}
                        dataSource={tableListData}
                        options={false}
                        search={false}
                        pagination={{
                            //分页
                            pageSize: 10,
                        }}
                        rowKey="key"
                    />
                </ProCard>
            </div>
        </PageContainer >
    );
};

export default connect(({ Model_Counsellor }: any) => ({
    Model_Counsellor,

}))(MessageList);
